package cn.tedu.account.tcc;

import cn.tedu.account.entity.Account;
import cn.tedu.account.mapper.AccountMapper;
import com.netflix.discovery.converters.Auto;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import java.math.BigDecimal;
@Component
@Slf4j
public class AccountTccActionImpl implements AccountTccAction {
    @Autowired
    private AccountMapper accountMapper;
    @Override
    @Transactional
    public boolean prepareDecreaseAccount(BusinessActionContext businessActionContext, Long userId, BigDecimal money) {
        log.info("减少账户金额，第一阶段锁定金额，userId="+userId+"， money="+money);
        Account account = accountMapper.selectById(userId);
        if (account.getResidue().compareTo(money)<0){
            throw new RuntimeException("账户余额不足");
        }
        accountMapper.updateFrozen(userId,
                account.getResidue().subtract(money),
                account.getFrozen().add(money));
        ResultHolder.setResult(getClass(),businessActionContext.getXid(),"p");
        return true;
    }

    @Override
    @Transactional
    public boolean commit(BusinessActionContext businessActionContext) {

        if (ResultHolder.getResult(getClass(),businessActionContext.getXid())==null){
            return true;
        }
        long userId = Long.valueOf(businessActionContext.getActionContext("userId").toString());
        BigDecimal money = new BigDecimal(businessActionContext.getActionContext("money").toString());
        log.info("减少账户金额，第二阶段，提交，userId="+userId+"， money="+money);
        accountMapper.updateFrozenToUsed(userId,money);
        ResultHolder.removeResult(getClass(),businessActionContext.getXid());
        return true;
    }

    @Override
    @Transactional
    public boolean rollback(BusinessActionContext businessActionContext) {
        if (ResultHolder.getResult(getClass(),businessActionContext.getXid())==null){
            return true;
        }
        long userId = Long.valueOf(businessActionContext.getActionContext("userId").toString());
        BigDecimal money = new BigDecimal(businessActionContext.getActionContext("money").toString());
        log.info("减少账户金额，第二阶段，回滚，userId="+userId+"， money="+money);
        accountMapper.updateFrozenToResidue(userId,money);
        ResultHolder.removeResult(getClass(),businessActionContext.getXid());

        return true;
    }
}
